﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using EPiServer.Core;
using EPiServer.Core.Html;

namespace EPiServer
{
    public static class Html
    {
        public static string Title(this PageReference pageRef)
        {
            if(PageReference.IsNullOrEmpty(pageRef))
                return "";

            var p = DataFactory.Instance.GetPage(pageRef);

            return p["Heading"] as string ?? p.PageName;
        }

        public static string ToLink(this PageReference pageRef)
        {
            return pageRef.ToLink("");
        }

        public static string ToLink(this PageReference pageRef, string cssClass)
        {
            if (PageReference.IsNullOrEmpty(pageRef))
                return string.Empty;

            string css = "";

            if (!string.IsNullOrEmpty(cssClass))
                css = string.Format(" class=\"{0}\"", cssClass);

            var pageData = EPiServer.DataFactory.Instance.GetPage(pageRef);
            return string.Format("<a href=\"{0}\"{2}>{1}</a>", pageData.LinkURL, pageData.PageName, css);
        }

        public static string ToUrl(this PageReference pageRef)
        {
            return DataFactory.Instance.GetPage(pageRef).LinkURL;
        }

        public static string Translate(string text)
        {
            return LanguageManager.Instance.Translate(text);
        }

        public static string GetPreview(Models.BaseModel model)
        {
            return GetPreview(model, 400);
        }

        public static string GetPreview(Models.BaseModel model, int length)
        {
            string htmlText = model.MainIntro;
            if (htmlText == null)
            {
                htmlText = model.MainBody;
            }
            if (htmlText == null)
            {
                return string.Empty;
            }

            return TextIndexer.StripHtml(htmlText, length);
        }

        public static string Resource(string resourceUrl)
        {
            //TODO: kolla om det finns någon skapad instans.. 
            var f = ResourceExpressionBuilder.ParseExpression(resourceUrl);
            var x = new Resources.GlobalXmlResourceProvider(f.ClassKey);
            return x.GetObject(f.ResourceKey, System.Threading.Thread.CurrentThread.CurrentUICulture).ToString();
        }
    }
}